import { ConfigureService } from '@app/configure';
import { Injectable } from '@nestjs/common';
import { getRandomValues } from 'crypto';

import * as tencentcloud from "tencentcloud-sdk-nodejs"

@Injectable()
export class SmsService {

    constructor(
        private readonly config:ConfigureService,
    ){}

    generateSecureRandomString(length = 6) {
        const characters = '0123456789';
        let result = '';
        const charactersLength = characters.length;
        const array = new Uint8Array(length);
    
        getRandomValues(array);
    
        for (let i = 0; i < length; i++) {
            result += characters[array[i] % charactersLength];
        }
    
        return result;
    }


    send(phone) {
        const code = this.generateSecureRandomString()
        //return code
        const smsConfig = this.config.get('sms')


        const smsClient = tencentcloud.sms.v20210111.Client
        const client = new smsClient({
            credential: {
                secretId: smsConfig.secretId,
                secretKey: smsConfig.secretKey,
            },

            region: smsConfig.region,
            profile: {
                signMethod: "HmacSHA256",
                httpProfile: {
                    reqMethod: "POST", // 请求方法
                    reqTimeout: 10, // 请求超时时间，默认60s
                    endpoint: "sms.tencentcloudapi.com"
                },
            },
        })

        const params = {
            SmsSdkAppId: smsConfig.SmsSdkAppId,
            SignName: smsConfig.SignName,
            TemplateId: smsConfig.TemplateId,
            TemplateParamSet: [code, "5"],
            PhoneNumberSet: ["+86" + phone],
        }

        client.SendSms(params, function (err, response) {
            //console.log(err)
            console.log(response)
            if (err) {
                console.log(err)
                return
            }
            //console.log(response)
        })

        return code
    }
}
